package com.example.blmap;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.locat.BeacoNode;
import com.example.locat.TrianBeacation;
import com.example.locat.abs.Point;

import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconManager;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

public class MainActivity extends Activity {

    public static final String TAG = "MainActivity";
    public static final String BEACON_ACTION = "com.example.beacondemo";
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private BeaconBroadcastReceiver beaconBroadcastReceiver;
    private ListView lvBeacons;
    private Button mBtnGotoBlMap;
    private MyAdapter myAdapter;
    private List<Beacon> beacs;
    private List<Beacon> forIntent;

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestLocationPermission();
        initViews();

        beaconBroadcastReceiver = new BeaconBroadcastReceiver();

        Intent intent = new Intent(MainActivity.this, BeaconService.class);
        startService(intent);



    }

    private void initViews() {
        beacs = new ArrayList<>();
        forIntent = new ArrayList<>();
        lvBeacons = (ListView) findViewById(R.id.lv_beacons);
        myAdapter = new MyAdapter(this,R.layout.beacons_view,beacs);
        lvBeacons.setAdapter(myAdapter);
        mBtnGotoBlMap = findViewById(R.id.btn_blescan);
        mBtnGotoBlMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(forIntent==null||forIntent.size() < 1){
                    Toast.makeText(MainActivity.this, "please select 3 beacons in this activity.", Toast.LENGTH_SHORT).show();
                    return ;
                }
                Intent intent = new Intent(MainActivity.this,BlMapActivity.class);
                intent.putParcelableArrayListExtra("selectedBeacon",(ArrayList<? extends Parcelable>) forIntent);
                startActivity(intent);
            }
        });
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(beaconBroadcastReceiver != null){
            unregisterReceiver(beaconBroadcastReceiver);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(beaconBroadcastReceiver,getBeaconIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(beaconBroadcastReceiver != null){
            unregisterReceiver(beaconBroadcastReceiver);
        }
    }
    Map<String,Beacon> beacMap = new HashMap();

    class BeaconBroadcastReceiver extends BroadcastReceiver{


        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BEACON_ACTION.equals(action)) {
                List<Beacon> beacons = intent.getParcelableArrayListExtra("beacon");
                Log.i(TAG, "onReceive: " + beacons.size());
                for (Beacon beacon : beacons) {

                    String address = beacon.getBluetoothAddress();
                    beacMap.put(address,beacon);


                }
                beacs.clear();
                for(Beacon bb : beacMap.values()){

                    beacs.add(bb);
                }
                //beacs.add(UUID.randomUUID()+"");
                myAdapter.setbeacs(beacs);
                myAdapter.notifyDataSetChanged();
                Log.i(TAG, "onReceive: " + "**********************************");
            }
        }
    }
    IntentFilter getBeaconIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BEACON_ACTION);
        return intentFilter;
    }



    class MyAdapter extends ArrayAdapter {
        private List<Beacon> beacs;
        private Context context;

        public MyAdapter( Context context, int resource,  List<Beacon> beacs) {
            super(context, resource, beacs);
            this.context = context;
            this.beacs = beacs;
        }

        public void setbeacs(List<Beacon> beacs){
            this.beacs = beacs;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            //View view = LayoutInflater.from(getContext()).inflate(R.id.rl_lv,parent,null);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.beacons_view,parent,false);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Beacon beacon = beacs.get(position);

                    if(!forIntent.contains(beacon)) {
                        forIntent.add(beacon);
                        Toast.makeText(context,""+beacon.getBluetoothAddress()+"   --  "+forIntent.size(),Toast.LENGTH_LONG).show();
                    }
                }
            });
            TextView tv = (TextView) view.findViewById(R.id.tv_list);
            //获取 uuid，major，minor
            Beacon beacon = beacs.get(position);
            String uuid = String.valueOf(beacon.getId1());
            String major = String.valueOf(beacon.getId2());
            String mMinor = String.valueOf(beacon.getId3());
            int minor = Integer.parseInt(mMinor);
            String address = beacon.getBluetoothAddress();
            String text = "UUID: " +beacon.getId1() + "\r\n" +
                    "Major: "+beacon.getId2() + "\r\n" +
                    "Minor: "+beacon.getId3()  + "\r\n" +
                    "Address: " + beacon.getBluetoothAddress() + "\r\n" +
                    "TxPower: " + beacon.getTxPower()  + "\r\n" +
                    "Rssi: " + beacon.getRssi() + "\r\n" +
                    "RssiAvg:" + new BigDecimal(beacon.getRunningAverageRssi()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue() + "\r\n" +
                    "Distance: " + new BigDecimal(beacon.getDistance()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue()+ "m";
            tv.setText(text);
            return view;
        }
    }

    private void requestLocationPermission() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if(this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case PERMISSION_REQUEST_COARSE_LOCATION:
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this, "PERMISSION_GRANTED", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
